import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import styles from './style.scss';
import actions from 'store/actions/app-configs';
import {List, Button, message, Modal} from 'antd';
const confirm = Modal.confirm;

class AppConfigs extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectItem: {}
    };
  }

  async componentWillMount() {
    const {dispatch} = this.props;
    dispatch(actions.queryAppConfigs());
  }

  async showEditor(item) {
    if (item && item.id) {
      const res = await this.props.dispatch(actions.queryById(item.id));
      if (res.code === '0') {
        let path = {
          pathname: '/appConfigs/editor',
          data: {
            ...res.data,
            type: 'edit'
          }
        };
        this.props.history.push(path);
      } else {
        message.error('网络异常');
      }
    } else {
      this.props.history.push('/appConfigs/editor');
    }
  }

  showConfirm(item) {
    this.setState({
      selectItem: item
    });
    const self = this;
    confirm({
      title: '确认删除这个配置吗?',
      content: '删除后将无法恢复',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return new Promise(async (resolve, reject) => {
          const {dispatch} = self.props;
          const res = await dispatch(actions.deleteById(self.state.selectItem.id));
          if (res.code === '0') {
            resolve();
            dispatch(actions.queryAppConfigs());
          } else {
            reject();
          }
        }).catch(() => message.error('删除失败！'));
      },
      onCancel() {}
    });
  }

  buildActions(item) {
    return [
      <a
        onClick={() => {
          this.showEditor(item, 'edit');
        }}
        role="presentation"
      >
        编辑查看
      </a>,
      <a
        onClick={() => {
          this.showConfirm(item);
        }}
        role="presentation"
      >
        删除
      </a>
    ];
  }

  render() {
    const configs = this.props.appConfigsState.configs;
    return (
      <div className={styles.wrap}>
        <div className={styles.handlers}>
          <Button
            type="primary"
            onClick={() => {
              this.showEditor();
            }}
          >
            添加
          </Button>
        </div>
        <List
          header={<div className={styles.header}>应用名</div>}
          bordered
          dataSource={configs}
          renderItem={(item) => <List.Item actions={this.buildActions(item)}>{item.appName}</List.Item>}
        />
      </div>
    );
  }
}

function select(state) {
  return state;
}

export default withRouter(connect(select)(AppConfigs));
